<script type="text/javascript" src="/public/js/my_plugin/lov.js"></script>
<?php
use Core\Config;
use Zend\Json\Json;

$allMenu = $this->allMenu;
$allSourceActivePage = $this->allActivePage;
$allAutoCompleteArr = array();
$allPageGridArr = array();

foreach ($allSourceActivePage as $aPage) {
   array_push($allAutoCompleteArr, $aPage->name.'---'.$aPage->myroute);
    array_push($allPageGridArr,array('name'=>$aPage->name.'---'.$aPage->myroute));
}

$allAutoCompleteJson = Json::encode($allAutoCompleteArr);
$allPageGridJson = Json::encode($allPageGridArr);


?>

<div class="ad_title_ctn">
    <h2>Quản lý menu (menu)</h2>
</div>

<div class="ad_content_ctn">

    <div class="menus_ctn left">

        <ul id="panelbar">
            <?php
            foreach ($allMenu as $aMenu) {
                $firstMenuId = $aMenu->id;
                echo ' <li id="panel_item'.$aMenu->id.'">
                <span class="title">'.$aMenu->name.'</span>
                <input class="txtHiddenMenuId" type="hidden" value="'.$aMenu->id.'">
                <div style="padding: 10px">
                    <div class="menu_ctrl_ctn">
                        <a id="btnAddMenu_'.$aMenu->id.'" class="k-button k-button-icontext k-grid-edit" href="#">
                            Thêm mới
                        </a>&nbsp;&nbsp;
                        <a id="btnDeleteMenu_'.$aMenu->id.'" class="k-button k-button-icontext k-grid-edit" href="#">
                            Xóa
                        </a>&nbsp;&nbsp;

                        <a id="btnUpMenu_'.$aMenu->id.'" style="display: none" class="k-button k-button-icontext k-grid-edit" href="#">
                            Up
                        </a>&nbsp;&nbsp;
                        <a id="btnDownMenu_'.$aMenu->id.'" style="display: none" class="k-button k-button-icontext k-grid-edit" href="#">
                            Down
                        </a>
                    </div>
                    <div class="menu_tree_ctn" id="menu_tree_ctn_'.$aMenu->id.'">

                    </div>
                </div>
            </li>';
            }

            ?>

        </ul>
    </div>
    <div class="menu_info_wrap left">
        <div class="none_menu_info_ctn">
            Chọn một menu để hiển thị thông tin hoặc click thêm mới menu.
        </div>

        <div class="menu_info_ctn " style="display: none">
            <div class="header">
                <span class="header_name"></span>
            </div>
            <div class="body" id="menuInfoCtn">
                <div id="noneMenu" style="display: none" >
                    <h4>Chọn một menu để hiển thị thông tin</h4>
                </div>
                <div id="realMenu" style="display: block">
                    <input type="hidden" id="txtMenuItemId">
                    <div id="menuInfo">
                        <div>
                            <div class="label_80 left">Tên(*):</div>
                            <div class="form_component_div left"><input class="k-textbox" id="txtMenuItemName" name="txtMenuItemName" required placeholder="Nhập text hiển thị menu" validationMessage="Chưa nhập tên">
                                <span class="k-invalid-msg" data-for="txtMenuItemName"></span>
                            </div>
                            <div class="clear"></div>
                        </div>

                        <div>
                            <div class="label_80 left">Url(*):</div>
                            <div class="form_component_div left">
                                <input class="k-textbox" id="txtMenuUrl" name="txtMenuUrl" required placeholder="Nhập url hoặc chọn trang" validationMessage="Chưa nhập url">
                                &nbsp;&nbsp;<a id="btnChoosePage" class="k-button k-button-icontext k-grid-edit" >...</a>
                                <span class="k-invalid-msg" data-for="txtMenuUrl"></span>
                            </div>
                            <div class="clear"></div>
                        </div>
                        <div id="parameterChooserBox">

                        </div>
                        <div>
                            <div class="label_80 left">Target:</div>
                            <div class="form_component_div left">
                                <select id="cboMenuTarget">
                                    <?php
                                    $allMenuTarget = Config::getAllMenuTarget();
                                    foreach ($allMenuTarget as $key => $val) {
                                        echo '<option value="'.$key.'">'.$val.'</option>';
                                    }
                                    ?>
                                </select>
                            </div>
                            <div class="clear"></div>
                        </div>

                    </div>
                    <div id="menuControlCtn">
                        <a  id="btnSave" class="k-button k-button-icontext k-grid-edit" href="#">Lưu</a>
                    </div>

                </div>


            </div>

        </div>
    </div>


    <div class="clear"></div>
</div>

<div id="wndPageChooser">
    <input id="txtPageSearch" style="width: 480px" />
    <div id="gridAllPages" style="margin: 10px 0px"></div>
</div>

<script type="text/javascript">
var validator;
$(document).ready(function() {
    var autoCompleteJsonData = <?php echo $allAutoCompleteJson ?>;
    var allPageGridJson = <?php echo $allPageGridJson ?>;
    var urlPrototype = '';
    var allParamMap = [];

    $("#panelbar").kendoPanelBar({
        expandMode: "single",
        select: onSelectAMenu
    });

    $("#txtPageSearch").kendoAutoComplete({
        dataSource: autoCompleteJsonData,
        filter: "startswith",
        placeholder: "Nhập tên trang để tìm kiếm",
        separator: "",
        dataBound: function(e) {
            value = this.value();
            filter = [];
            grid = $("#gridAllPages").data("kendoGrid");
            if (value) {
                filter.push({ field:"name", operator:"startswith", value:value});

                grid.dataSource.filter(filter);
            }
        },
        close: function(e) {
            grid = $("#gridAllPages").data("kendoGrid");
                grid.dataSource.filter([]);
        },
        change: function(e) {
            pageInfo = this.value();
            wndPageChooser.close();
            route = pageInfo.substr(pageInfo.indexOf('---') + 3);

            $('#txtMenuUrl').val(route)
            $('#txtMenuUrl').trigger('change');
        }
    });

    $("#cboMenuTarget").kendoComboBox();
    var cboMenuTarget = $("#cboMenuTarget").data("kendoComboBox");
    var wndPageChooser = $("#wndPageChooser")
            .kendoWindow({
                title: "Chọn trang",
                modal: true,
                visible: false,
                resizable: false,
                width: 500,
                activate: onActivateChoosePage

            }).data("kendoWindow");
    $("#wndPageChooser").keypress(function(event){
        if (event.keyCode === 27) {
            $("#wndPageChooser").data("kendoWindow").close();
        }
    });

    $('#txtMenuUrl').change(function(){
        route = $(this).val();
        urlPrototype = route;
        initParamMap();

        $.post('/admin/menu/get-parameter-box',{url:route},function(result){
            $('#parameterChooserBox').html(result);
            $('.txt_param_holder').each(function(){
                paramValue = $(this).val();
                paramName = $(this).prev().text();
                tmpUrl = buildUrl(paramName, paramValue);
                $('#txtMenuUrl').val(tmpUrl);
                $(this).change(function(){
                    paramValue = $(this).val();
                    paramName = $(this).prev().text();
                    tmpUrl = buildUrl(paramName, paramValue);
                    $('#txtMenuUrl').val(tmpUrl);
                })
            })
        });
    })

    function initParamMap(){
        tmpArr = urlPrototype.split(':');
        allParamMap = [];
        if(tmpArr.length > 1)
        for ( obj in tmpArr) {
            if(obj > 0){
                tmpVal = tmpArr[obj];
                fooArr = tmpVal.split('/');
                allParamMap[fooArr[0]] = '';
            }
        }
    }


    function buildUrl(paramName, paramValue){
        allParamMap[paramName] = paramValue;
        tmpUrl = urlPrototype;

        for ( obj in allParamMap) {
            if(allParamMap[obj]){
                tmpStr = ':'+ obj;
                tmpUrl = tmpUrl.replace(tmpStr,allParamMap[obj] );
            }
        }
        return tmpUrl;
    }


    $("#gridAllPages").kendoGrid({
        dataSource: {
         data:allPageGridJson,
            type: 'json',
            pageSize: 10
        },
        navigatable: true,
        pageable: true,
        sortable: true,
        selectable:'single',
        columns: [
            { field: "name", title: "Name", width: 120 }

        ]

    });
    $("#gridAllPages").delegate("tbody>tr", "dblclick", function(){
        grid = $("#gridAllPages").data("kendoGrid");
        pageInfo = grid.select().text();
        wndPageChooser.close();
        route = pageInfo.substr(pageInfo.indexOf('---') + 3);
        $('#txtMenuUrl').val(route)
        $('#txtMenuUrl').trigger('change');

    });



    function onActivateChoosePage(){
        $("#txtPageSearch").focus();
    }

    function chooseAPage(){

    }

    $('#btnChoosePage').click(function(){
        wndPageChooser.center().open();
    });

    function onSelectAMenu(e){

        menuId = $(e.item).find("input.txtHiddenMenuId").val();
        loadMenuTree(menuId);
    }

    function loadMenuTree(menuId){
        if(!menuId) return;
        $(".menu_tree_ctn").each(function(){
            $(this).html('');
            $(this).removeClass('k-widget k-treeview');
        })

        contentContainer = $('#menu_tree_ctn_'+menuId);
        $.post('<?php echo '/admin/menu/get-menu-content'  ?>',
                {menuId:menuId}
                ,function(result){
                    contentContainer.html(result);
                });

    }

    var firstMenu = <?php echo $firstMenuId?>;
    if(firstMenu){
        loadMenuTree(firstMenu);
        panelBar = $("#panelbar").data("kendoPanelBar");
        panelBar.expand('#panel_item'+firstMenu);
        //expand first panel

    }


    $('[id^=btnAddMenu]').click(function(){
        selectedNode = getTreeSelectedNode(treeview)
        data = treeview.dataItem(selectedNode);
        doAdd(data)

    });


    $('[id^=btnDeleteMenu]').click(function(){
        selectedNode = getTreeSelectedNode(treeview)
        data = treeview.dataItem(selectedNode);
        r=confirm("Bạn có chắc chắn xóa menu: "+ data.label )
        if (r==true)
        {
            deleteMenu(data,treeview)
        }


    });
    $('[id^=btnUpMenu]').click(function(){
        selectedNode = getTreeSelectedNode(treeview)
        data = treeview.dataItem(selectedNode);
        upMenu(data,treeview)

    });
    $('[id^=btnDownMenu]').click(function(){
        selectedNode = getTreeSelectedNode(treeview)
        data = treeview.dataItem(selectedNode);
        downMenu(data,treeview)
    });

    validator = $(".menu_info_ctn").kendoValidator().data("kendoValidator");
    $('#btnSave').click(function(){
        saveMenu();
    })

    function validate(){

        return validator.validate();
    }


    function getParent(menuNode, treeview){
        parentNode = treeview.parent(menuNode)
        if (parentNode.length == 0) {
            treeview.select(".k-item:first");
            parentNode = treeview.select();
        }
        return parentNode;
    }

    function doAdd(data){
        $('.none_menu_info_ctn').hide();
        $('.menu_info_ctn').show();

        $('.header_name').html('Thêm mới menu item vào menu item cha: '+ data.label);

        $('#txtMenuItemName').val('');
        $('#txtMenuItemId').val('');
        $('#txtMenuUrl').val('');
        $('#parameterChooserBox').html('');
        parentMenuId = data.id;

    }





    function saveMenu(){
        if(!validate())
            return;
        menuName = $('#txtMenuItemName').val();
        id = $('#txtMenuItemId').val();
        url = $('#txtMenuUrl').val();
        selectedNode = getTreeSelectedNode(treeview)
        data = treeview.dataItem(selectedNode);
        parenMenuId = data.id;
        target = cboMenuTarget.value();
        menu_id = data.menu_id
        $.post('<?php echo '/admin/menu/save-menu-item'  ?>',
                {parentId:data.id, id:id, url:url, name:menuName,target:target}
                ,function(result){
                    if (result.success){

                        if(id)
                            $('#error_ctn').addClass('blue_text').html('Sửa menu '+menuName+' thành công.');
                        else{
                            $('#error_ctn').addClass('blue_text').html('Thêm menu '+menuName+' thành công.');

                            doAdd(data)    ;
                        }


                        loadMenuTree(menu_id);


                    }else{
                        $('#error_ctn').removeClass('blue_text').html(result.msg);
                        alert(result.msg);
                    }
                },'json');
    }





    function deleteMenu(data,treeview){
         $.post('<?php echo '/admin/menu/remove-menu-item'  ?>',
                {id:data.id}
                ,function(result){
                    if (result.success){
                        selectedNode = getTreeSelectedNode(treeview)
                        treeview.remove(selectedNode);
                        $('[id^=btnUpMenu]').hide();
                        $('[id^=btnDownMenu]').hide();
                        $('#error_ctn').addClass('blue_text').html('Xóa menu: <b>'+ data.label + '</b> thành công');
                        loadMenuTree(data.menu_id);
                        $('.none_menu_info_ctn').show();
                        $('.menu_info_ctn').hide();

                    }else{
                        $('#error_ctn').removeClass('blue_text').html(result.msg);
                        alert(result.msg);
                    }
                },'json');

    }

    function upMenu(data,treeview){
         $.post('<?php echo '/admin/menu/up-menu-item'  ?>',
                {id:data.id}
                ,function(result){
                    if (result.success){
                        $('#error_ctn').addClass('blue_text').html('Đổi thứ tự menu: <b>'+ data.label + '</b> thành công');
                        loadMenuTree(data.menu_id);
                    }else{
                        $('#error_ctn').removeClass('blue_text').html(result.msg);
                        alert(result.msg);
                    }
                },'json');

    }

    function downMenu(data,treeview){
        $.post('<?php echo '/admin/menu/down-menu-item'  ?>',
                {id:data.id}
                ,function(result){
                    if (result.success){
                        $('#error_ctn').addClass('blue_text').html('Đổi thứ tự menu: <b>'+ data.label + '</b> thành công');
                        loadMenuTree(data.menu_id);
                    }else{
                        $('#error_ctn').removeClass('blue_text').html(result.msg);
                        alert(result.msg);
                    }
                },'json');
    }
});

</script>